package ch12;

class ThreadEx11 {
	public static void main(String args[]) {
		ThreadEx11_1 gc = new ThreadEx11_1();
		gc.setDaemon(true);
		gc.start();

		int requiredMemory = 0;

		for (int i = 0; i < 20; i++) {
			requiredMemory = (int) (Math.random() * 10) * 20;
			if (gc.freeMemory() < requiredMemory || gc.freeMemory() < gc.totalMemory() * 0.4){ 
				gc.interrupt();
				try{gc.join(1000);}catch(InterruptedException e){}
			}
			gc.usedMemory += requiredMemory;
			System.out.println("usedMemory:" + gc.usedMemory);
		}
	}
}

class ThreadEx11_1 extends Thread {
	final static int MAX_MEMORY = 1000;
	int usedMemory = 0;

	public void run() {
		while (true) {
			try {
				Thread.sleep(10 * 1000); 
			} catch (InterruptedException e) {
				System.out.println("Awaken by interrupt().");
			}

			gc();
			System.out.println("Garbage Collected. Free Memory :" + freeMemory());
		}
	}

	public void gc() {
		usedMemory -= 300;
		if (usedMemory < 0)	usedMemory = 0;
	}

	public int totalMemory() {
		return MAX_MEMORY;
	}

	public int freeMemory() {
		return MAX_MEMORY - usedMemory;
	}
}
/*
usedMemory:100
usedMemory:240
usedMemory:320
usedMemory:480
usedMemory:660
Awaken by interrupt().
Garbage Collected. Free Memory :640
usedMemory:380
usedMemory:520
usedMemory:600
usedMemory:680
Awaken by interrupt().
Garbage Collected. Free Memory :620
usedMemory:400
usedMemory:540
usedMemory:620
Awaken by interrupt().
Garbage Collected. Free Memory :680
usedMemory:400
usedMemory:540
usedMemory:580
usedMemory:600
usedMemory:680
Awaken by interrupt().
Garbage Collected. Free Memory :620
usedMemory:480
usedMemory:500
usedMemory:620
*/